package com.example.talksdk;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import UserAdapter.ChatAdapter;
import UserAdapter.FriendsAdapter;
import UserClientSocket.Client;
import UserDecoration.SpacesItemDecoration;
import UserGlobal.GlobalData;
import UserThread.ChatMesRecieveThread;
import UserThread.ChatMesSendThread;
import UserThread.DeleteThread;

//聊天界面Ui操作
public class ChatUi extends AppCompatActivity implements View.OnClickListener {
    RecyclerView mRecyclerView;
    Boolean isSkip = false;
    LinearLayoutManager mLinearLayoutManager;
    ChatAdapter mChatAdapter;
    EditText mEditText;
    ChatMesSendThread mSendThread = new ChatMesSendThread();
    ChatMesRecieveThread thread;
    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat_ui);
        init();//加载聊天历史
        Toolbar mToolbar = findViewById(R.id.chattoolbar);
        mEditText = findViewById(R.id.chatedit);
        setSupportActionBar(mToolbar);
        mToolbar.setTitle(GlobalData.Friendid);
        Button mChatSendButton = findViewById(R.id.chatsendbutton);//chatui发送按钮
        mRecyclerView = findViewById(R.id.chatrecycleview);
        mLinearLayoutManager = new LinearLayoutManager(ChatUi.this);
        mChatAdapter = new ChatAdapter();
        mRecyclerView.setLayoutManager(mLinearLayoutManager);
        mRecyclerView.setAdapter(mChatAdapter);
        mRecyclerView.addItemDecoration(new SpacesItemDecoration(30));
        mChatSendButton.setOnClickListener(this);
        GlobalData.activity = ChatUi.this;//初始化全局activity
        GlobalData.action = new Runnable() {//初始化全局action
            @Override
            public void run() {
                mRecyclerView.scrollToPosition(mChatAdapter.getItemCount() - 1);
                mChatAdapter.notifyDataSetChanged();
                int index1 = GlobalData.mHistoryId.indexOf(GlobalData.Friendid);
                if(index1!=-1){
                    GlobalData.mGravityList = GlobalData.mChatHistory.get(index1);
                }
            }
        };
        final View rootView = ChatUi.this.getWindow().getDecorView();
        rootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            int diff = 0;
            @Override
            public void onGlobalLayout() {
                Rect rect = new Rect();
                rootView.getWindowVisibleDisplayFrame(rect);
                int rootheight = rootView.getHeight();
                int visiableheight = rect.height();
                if (diff != rootheight - visiableheight) {
                    diff = rootheight - visiableheight;
                    if (diff > 600) {
                        mRecyclerView.scrollToPosition(mChatAdapter.getItemCount() - 1);
                    }
                }
            }
        });
    }
    //载入聊天记录
    void init() {
        int index = GlobalData.mHistoryId.indexOf(GlobalData.Friendid);
        Log.d("haha", String.valueOf(index));
        if (index != -1) {
            GlobalData.mGravityList = GlobalData.mChatHistory.get(index);
        }else{
            GlobalData.mGravityList=new ArrayList<>();
        }
    }
    //保存当前聊天记录
    void savehistory() {
        GlobalData.Friendmes = "";
        GlobalData.action = null;
        GlobalData.activity = null;
    }
    @Override
    protected void onStop() {
        if (!isSkip) {
            new DeleteThread(GlobalData.Myid).start();
            GlobalData.Myid = "";
            finish();
        }
        super.onStop();
    }
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            isSkip = true;
            savehistory();
        }
        return super.onOptionsItemSelected(item);
    }
    //系统返回监听
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            isSkip = true;
            Log.d("haha","yes");
            savehistory();
        }
        return super.onKeyDown(keyCode, event);
    }
    @Override
    public void onClick(View v) {
        if (!mRecyclerView.isComputingLayout()) {
            if (v.getId() == R.id.chatsendbutton) {
                String mes = mEditText.getText().toString();
                //判断发送信息是否为空
                if (mes.length() != 0 && !mSendThread.isRunning) {
                    Runnable action = new Runnable() {
                        @Override
                        public void run() {
                            mRecyclerView.scrollToPosition(mChatAdapter.getItemCount() - 1);
                            mChatAdapter.notifyDataSetChanged();
                            int index1 = GlobalData.mHistoryId.indexOf(GlobalData.Friendid);
                            GlobalData.mGravityList = GlobalData.mChatHistory.get(index1);
                        }
                    };
                    mSendThread = new ChatMesSendThread(ChatUi.this, action, mes);
                    mSendThread.start();
                    mEditText.setText("");
                } else {
                    mSendThread=new ChatMesSendThread();
                    Toast.makeText(ChatUi.this, "message is sending or null", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }
}